package com.menker.app.ui.main;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.github.sahasbhop.apngview.ApngImageLoader;
import com.menker.app.Constants;
import com.menker.app.R;
import com.menker.app.biz.WebPageInfo;
import com.menker.app.common.BaseToolbarFragment;
import com.menker.app.common.Utils;
import com.menker.app.rest.ApiHelper;
import com.menker.app.rest.result.ChannelInfo;
import com.menker.app.util.IntentUtils;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;

import static com.menker.app.Constants.API.ENDPOINT;

/**
 * @version 1.0
 */
@EFragment(R.layout.frag_home)
public class HomeFragment extends BaseToolbarFragment {

    @ViewById(R.id.frag_home_tab_layout)
    SlidingTabLayout mTabLayout;
    @ViewById(R.id.frag_home_tab_view_pager)
    ViewPager mViewPager;
    @ViewById(R.id.search_giv_act)
    ImageView mImage;

    @StringRes(R.string.error_api)
    String mStrApiError;

    private Subscriber<ChannelInfo> mGetAllChannelSubscriber = null;

    private ArrayList<Fragment> mFragmentList = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private final String DEFAULT_URL = ENDPOINT + "App_Content/views/event/index.html";
    private ApiHelper mApiHelper;


    @AfterViews
    void initUI() {
        mFragmentList.clear();
        mTabEntities.clear();

        mApiHelper = ((MainActivity_) getActivity()).getApiHelper();

        mGetAllChannelSubscriber = new GetAllChannelSubscriber();
        mApiHelper.getAllChannel(mGetAllChannelSubscriber);

        String uri = "assets://apng/btn_pt_no.png";
        ApngImageLoader.getInstance().displayApng(uri, mImage,
                new ApngImageLoader.ApngConfig(0, true));

        mImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.toNewGeneralWebViewActivity(HomeFragment.this, new WebPageInfo("", DEFAULT_URL));
            }
        });

    }

    @Override
    public void onDestroy() {
        if (mGetAllChannelSubscriber != null) {
            mGetAllChannelSubscriber.unsubscribe();
            mGetAllChannelSubscriber = null;
        }
        super.onDestroy();
    }

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        if (mFragmentList.size() > 0) {
//            Fragment fragment = mFragmentList.get(mTabLayout.getCurrentTab());
//            ((WebViewFragment_)fragment).reloadWebView();
//        }
//    }

    @Override
    protected void findViews() {

    }

    private class GetAllChannelSubscriber extends Subscriber<ChannelInfo> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mStrApiError);
        }

        @Override
        public void onNext(final ChannelInfo channelInfo) {
            if (channelInfo != null && channelInfo.checkState(getActivity())) {
                if (channelInfo.ChannelList != null && channelInfo.ChannelList.size() > 0) {

                    sortChannelList(channelInfo.ChannelList);

                    String[] titles = new String[mChannelList.size()];

                    for (int i = 0; i < mChannelList.size(); i++) {
                        Fragment fragment;

                        WebPageInfo webPageInfo0 = new WebPageInfo(mChannelList.get(i).Url, false);
                        fragment = WebViewFragment_.builder().webPageInfo(webPageInfo0).build();

                        if (fragment != null) {
//                            mTabEntities.add(new TabEntity(mChannelList.get(i).Title, 0, 0));
                            titles[i] = mChannelList.get(i).Title;
                            mFragmentList.add(fragment);
                        }
                    }

                    if (mTabLayout.getTabCount() == 0) {
                        mTabLayout.setViewPager(mViewPager, titles, getActivity(), mFragmentList);
                    }else {
                        mTabLayout.notifyDataSetChanged();
                    }
//                    mTabLayout.setTabData(mTabEntities, getActivity(), R.id.frag_home_layout_content, mFragmentList);

                    mTabLayout.setCurrentTab(0);

                }
            }
        }
    }

    private ArrayList<ChannelInfo.ChannelItem> mChannelList = new ArrayList<>();

    private void sortChannelList(List<ChannelInfo.ChannelItem> channelList) {
        if (channelList.size() <= 0) {
            return;
        }

        ChannelInfo.ChannelItem item = channelList.get(0);
        for (int j = 0; j < channelList.size(); j ++) {
            if (item.SortIndex > channelList.get(j).SortIndex) {
                item = channelList.get(j);
            }
        }

        mChannelList.add(item);

        channelList.remove(item);

        sortChannelList(channelList);
    }

    @Click(R.id.search_iv_page)
    void toSearchPage() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }
        String url = ENDPOINT + "/App_Content/views/home/search2.html";
        WebPageInfo webPageInfo = new WebPageInfo("", url);
        IntentUtils.toNewGeneralWebViewActivity(this, webPageInfo);
    }

    @Click(R.id.search_iv_list)
    void toListPage() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }
        String url = ENDPOINT + "/App_Content/views/product/cate.html";
        WebPageInfo webPageInfo = new WebPageInfo("", url);
        IntentUtils.toNewGeneralWebViewActivity(this, webPageInfo);
    }

    public void notifySearchView(int num, final String url) {

        String uri;

        if (num == 0) {
            uri = "assets://apng/btn_pt_no.png";
        }else {
            uri = "assets://apng/btn_pt_have.png";
        }

        ApngImageLoader.getInstance().displayApng(uri, mImage,
                new ApngImageLoader.ApngConfig(0, true));


        mImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtils.toNewGeneralWebViewActivity(HomeFragment.this, new WebPageInfo("", TextUtils.isEmpty(url) ? DEFAULT_URL : url));
            }
        });
    }

}
